package com.atguigu.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.CaseFormat;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 晶晶
 * @Date 2023 03 27 16 19
 **/
public class JdbcUtil_lj {
    public static <T> List<T> getJdbcUtil(Connection connection,String sql,Class<T> clz, boolean type) throws Exception{

        ArrayList<T> list = new ArrayList<>();

        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();


        //拿到每一行
        while (resultSet.next()) {
            //将每行封装为t对象
            T instance = clz.newInstance();
            for (int i = 0; i < columnCount; i++) {
                //获取列名 列值
                String columnName = metaData.getColumnName(i + 1);
                Object value = resultSet.getObject(columnName);

                //判断是否修改
                if(type){
                    columnName= CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,columnName.toLowerCase());
                }

                BeanUtils.setProperty(instance,columnName,value);
            }

            list.add(instance);

        }

        return list;

    }
}
